package com.jianying.day10;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.kafka.clients.producer.ProducerConfig;

/**
 * ClassName: Flink01_2pc_sink
 * Package: com.atguigu.day10
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/12 10:24
 * @Version: 1.0
 */
public class Flink01_2pc_sink {
    public static void main(String[] args) throws Exception {
        // TODO 从端口读数据，写到kafka主题

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 1 写入精准一次设置：检查点  barrier对齐精准一次
        env.enableCheckpointing(10000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60000L);

        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);

        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setBootstrapServers("localhost:9092,localhost:9093,localhost:9094")
                .setRecordSerializer(
                        KafkaRecordSerializationSchema.<String>builder()
                                .setTopic("first")
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .build()
                )
                .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE) // TODO 2 kafkaSink kafkaWriter 底层开启事务
                .setTransactionalIdPrefix("flink01_2pc_sink") // TODO 2 事务ID
                // TODO 3 检查点成功后正式提交 检查点超时时间 < 事务超时时间 <= 事务最大超时时间(默认15分钟)
                .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, 15*60*1000 + "")
                .build();

        socketDS.sinkTo(kafkaSink);
        env.execute();
    }
}
